<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文章管理</title>
    <link rel="stylesheet" href="/libs/element-plus.css">
    <style>
        body {
            margin: 0;
            padding: 20px;
            background-color: #f5f7fa;
            font-family: Arial, sans-serif;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        
        .card {
            background: white;
            border-radius: 4px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            padding: 20px;
            margin-bottom: 20px;
        }
        
        .form-item {
            margin-bottom: 15px;
        }
        
        .form-item label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        
        .form-item input, .form-item select, .form-item textarea {
            width: 100%;
            padding: 8px;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            box-sizing: border-box;
        }
        
        .form-item textarea {
            min-height: 200px;
            resize: vertical;
        }
        
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 10px;
        }
        
        .btn-primary {
            background-color: #409eff;
            color: white;
        }
        
        .btn-default {
            background-color: #ecf5ff;
            color: #409eff;
        }
        
        .btn-success {
            background-color: #67c23a;
            color: white;
        }
        
        .btn-warning {
            background-color: #e6a23c;
            color: white;
        }
        
        .btn-danger {
            background-color: #f56c6c;
            color: white;
        }
        
        .table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .table th, .table td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #eee;
        }
        
        .table th {
            background-color: #f5f7fa;
            font-weight: bold;
        }
        
        .status-draft {
            color: #909399;
        }
        
        .status-published {
            color: #67c23a;
        }
        
        .status-unpublished {
            color: #f56c6c;
        }
        
        .actions {
            white-space: nowrap;
        }
        
        .action-btn {
            background: none;
            border: none;
            color: #409eff;
            cursor: pointer;
            margin-right: 5px;
        }
        
        .loading {
            text-align: center;
            padding: 20px;
        }
        
        .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #409eff;
            border-radius: 50%;
            width: 30px;
            height: 30px;
            animation: spin 1s linear infinite;
            margin: 0 auto;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .search-form {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }
        
        .search-form input, .search-form select {
            flex: 1;
            padding: 8px;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
        }
        
        .search-form .btn {
            margin-right: 0;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h2>文章管理</h2>
            <button class="btn btn-primary" onclick="openEditor()">添加文章</button>
        </div>
        
        <div class="card">
            <div class="search-form">
                <input type="text" id="searchTitle" placeholder="搜索文章标题">
                <select id="searchCategory">
                    <option value="">所有分类</option>
                </select>
                <select id="searchStatus">
                    <option value="">所有状态</option>
                    <option value="0">草稿</option>
                    <option value="1">已发布</option>
                    <option value="2">已下架</option>
                </select>
                <button class="btn btn-primary" onclick="searchArticles()">搜索</button>
            </div>
            
            <div id="loadingIndicator" class="loading" style="display: none;">
                <div class="spinner"></div>
                <p>加载中...</p>
            </div>
            
            <table class="table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>标题</th>
                        <th>分类</th>
                        <th>作者</th>
                        <th>状态</th>
                        <th>发布时间</th>
                        <th>创建时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="articleList">
                    <!-- 文章列表将通过JavaScript动态加载 -->
                </tbody>
            </table>
        </div>
    </div>

    <script src="/libs/vue.global.prod.js"></script>
    <script src="/libs/element-plus.js"></script>
    <script src="/js/http-client.js"></script>
    
    <script>
        // 当前文章数据
        let articles = [];
        let categories = [];
        let editingArticle = null;
        
        // 页面加载完成后获取数据
        document.addEventListener('DOMContentLoaded', async function() {
            showLoading(true);
            await Promise.all([
                loadArticles(),
                loadAuthorizedCategories()
            ]);
            renderArticleList();
            updateSearchCategoryOptions();
            showLoading(false);
        });
        
        // 显示/隐藏加载指示器
        function showLoading(show) {
            const loadingIndicator = document.getElementById('loadingIndicator');
            const articleList = document.getElementById('articleList');
            
            if (show) {
                loadingIndicator.style.display = 'block';
                articleList.style.display = 'none';
            } else {
                loadingIndicator.style.display = 'none';
                articleList.style.display = 'table-row-group';
            }
        }
        
        // 加载文章数据
        async function loadArticles() {
            try {
                articles = await httpClient.get('/article/list');
            } catch (error) {
                console.error('获取文章数据异常:', error);
            }
        }
        
        // 加载授权的分类数据
        async function loadAuthorizedCategories() {
            try {
                categories = await httpClient.get('/category/authorized');
                console.log('加载到分类数据:', categories);
            } catch (error) {
                console.error('获取分类数据异常:', error);
                // 如果获取授权分类异常，回退到获取所有分类
                await loadCategories();
            }
        }
        
        // 加载所有分类数据（备用方法）
        async function loadCategories() {
            try {
                categories = await httpClient.get('/category/tree');
                console.log('加载到所有分类数据:', categories);
            } catch (error) {
                console.error('获取分类数据异常:', error);
            }
        }
        
        // 渲染文章列表
        function renderArticleList() {
            const container = document.getElementById('articleList');
            container.innerHTML = '';
            
            if (articles.length > 0) {
                articles.forEach(article => {
                    const row = document.createElement('tr');
                    
                    // 获取分类名称
                    const categoryName = getCategoryName(article.categoryId, categories) || '未知分类';
                    
                    // 获取状态文本
                    const statusText = getStatusText(article.status);
                    const statusClass = getStatusClass(article.status);
                    
                    // 格式化日期
                    const publishTime = article.publishTime ? new Date(article.publishTime).toLocaleString() : '-';
                    const createTime = new Date(article.createdAt).toLocaleString();
                    
                    row.innerHTML = `
                        <td>${article.id}</td>
                        <td>${article.title}</td>
                        <td>${categoryName}</td>
                        <td>${article.authorId}</td>
                        <td class="${statusClass}">${statusText}</td>
                        <td>${publishTime}</td>
                        <td>${createTime}</td>
                        <td class="actions">
                            <button class="action-btn" onclick="openEditor(${article.id})">编辑</button>
                            ${article.status == 1 ? 
                                `<button class="action-btn" onclick="unpublishArticle(${article.id})">下架</button>` :
                                `<button class="action-btn" onclick="publishArticle(${article.id})">发布</button>`
                            }
                            <button class="action-btn" onclick="deleteArticle(${article.id})">删除</button>
                        </td>
                    `;
                    
                    container.appendChild(row);
                });
            } else {
                const row = document.createElement('tr');
                row.innerHTML = '<td colspan="8" style="text-align: center;">暂无文章数据</td>';
                container.appendChild(row);
            }
        }
        
        // 获取分类名称
        function getCategoryName(categoryId, categories) {
            for (const category of categories) {
                if (category.id === categoryId) {
                    return category.name;
                }
                if (category.children && category.children.length > 0) {
                    const name = getCategoryName(categoryId, category.children);
                    if (name) return name;
                }
            }
            return null;
        }
        
        // 获取状态文本
        function getStatusText(status) {
            switch (status) {
                case 0: return '草稿';
                case 1: return '已发布';
                case 2: return '已下架';
                default: return '未知';
            }
        }
        
        // 获取状态样式类
        function getStatusClass(status) {
            switch (status) {
                case 0: return 'status-draft';
                case 1: return 'status-published';
                case 2: return 'status-unpublished';
                default: return '';
            }
        }
        
        // 更新分类选项
        function updateCategoryOptions() {
            // 注意：此函数已不再需要，因为我们已经移除了模态框表单
            // 保留此函数以避免JavaScript错误
            console.log('updateCategoryOptions 被调用，但不再需要');
        }
        
        // 更新搜索分类选项
        function updateSearchCategoryOptions() {
            const categorySelect = document.getElementById('searchCategory');
            
            console.log('更新搜索分类选项:', categories);
            
            function addOptions(cats, prefix = '') {
                cats.forEach(cat => {
                    const option = document.createElement('option');
                    option.value = cat.id;
                    option.textContent = prefix + cat.name;
                    categorySelect.appendChild(option);
                    
                    if (cat.children && cat.children.length > 0) {
                        addOptions(cat.children, prefix + '　');
                    }
                });
            }
            
            // 保留第一个选项（所有分类）
            const firstOption = categorySelect.firstElementChild;
            categorySelect.innerHTML = '';
            categorySelect.appendChild(firstOption);
            
            // 只有当有分类数据时才添加选项
            if (categories && categories.length > 0) {
                addOptions(categories);
            }
        }
        
        // 在新窗口中打开编辑器
        function openEditor(articleId) {
            const url = articleId ? `/article/editor?id=${articleId}` : '/article/editor';
            window.open(url, '_blank');
        }
        
        // 删除文章
        async function deleteArticle(id) {
            if (!confirm('确定要删除该文章吗？')) {
                return;
            }
            
            try {
                await httpClient.delete(`/article/${id}`);
                alert('删除成功');
                showLoading(true);
                await loadArticles();
                showLoading(false);
                renderArticleList();
            } catch (error) {
                console.error('删除文章异常:', error);
                alert('删除文章时发生错误');
            }
        }
        
        // 发布文章
        async function publishArticle(id) {
            try {
                await httpClient.post(`/article/${id}/publish`);
                alert('发布成功');
                showLoading(true);
                await loadArticles();
                showLoading(false);
                renderArticleList();
            } catch (error) {
                console.error('发布文章异常:', error);
                alert('发布文章时发生错误');
            }
        }
        
        // 下架文章
        async function unpublishArticle(id) {
            try {
                await httpClient.post(`/article/${id}/unpublish`);
                alert('下架成功');
                showLoading(true);
                await loadArticles();
                showLoading(false);
                renderArticleList();
            } catch (error) {
                console.error('下架文章异常:', error);
                alert('下架文章时发生错误');
            }
        }
        
        // 搜索文章
        async function searchArticles() {
            // 简单实现，实际项目中应该发送请求到后端进行搜索
            const title = document.getElementById('searchTitle').value.toLowerCase();
            const categoryId = document.getElementById('searchCategory').value;
            const status = document.getElementById('searchStatus').value;
            
            // 这里只是模拟过滤，实际应该发送到后端处理
            showLoading(true);
            await loadArticles(); // 重新加载所有数据
            
            // 应用过滤条件
            let filteredArticles = articles;
            if (title) {
                filteredArticles = filteredArticles.filter(a => a.title.toLowerCase().includes(title));
            }
            if (categoryId) {
                filteredArticles = filteredArticles.filter(a => a.categoryId == categoryId);
            }
            if (status !== '') {
                filteredArticles = filteredArticles.filter(a => a.status == status);
            }
            
            articles = filteredArticles;
            showLoading(false);
            renderArticleList();
        }
    </script>
</body>
</html>